package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.*;
import cn.wolfcode.wolf2w.query.StrategyCatalogQuery;
import cn.wolfcode.wolf2w.query.StrategyQuery;
import cn.wolfcode.wolf2w.redis.IStrategyRedisService;
import cn.wolfcode.wolf2w.repository.StrategyRepository;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.util.RedisKeys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class StrategyServiceImpl implements IStrategyService {

    @Autowired
    private StrategyRepository strategyRepository;

    @Autowired
    private StrategyCatalogServiceImpl strategyCatalogService;

    @Autowired
    private DestinationServiceImpl destinationService;

    @Autowired
    private StrategyThemeServiceImpl strategyThemeService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void save(Strategy strategy) {
        strategy.setId(null);
        strategyRepository.save(strategy);
    }

    @Override
    public void update(Strategy strategy) {
        strategyRepository.save(strategy);
    }

    @Override
    public void delete(String id) {
        strategyRepository.deleteById(id);
    }

    @Override
    public Strategy get(String id) {
        return strategyRepository.findById(id).get();
    }

    @Override
    public List<Strategy> list() {
        return strategyRepository.findAll();
    }

    @Override
    public Page<Strategy> query(StrategyQuery qo) {
        Query query = new Query();

        Long totalCount = mongoTemplate.count(query, Strategy.class);

        Pageable pageable= PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"_id");

        query.with(pageable);

        List<Strategy> strategies = mongoTemplate.find(query, Strategy.class);

        return new PageImpl(strategies,pageable,totalCount);
    }

    @Override
    public void saveOrUpdate(Strategy strategy) {
        //通过攻略对象中的目录id查询目录对象
        StrategyCatalog strategyCatalog = strategyCatalogService.get(strategy.getCatalogId());
        //在通过目录对象获取目的地id，目的地名字，目录名字
        strategy.setDestId(strategyCatalog.getDestId());
        strategy.setDestName(strategyCatalog.getDestName());
        strategy.setCatalogName(strategyCatalog.getName());
        //通过攻略对象中的攻略主题id查询主题对象
        StrategyTheme strategyTheme = strategyThemeService.get(strategy.getThemeId());
        //在通过主题对象获取主题名字
        strategy.setThemeName(strategyTheme.getName());

        //是否国外判断,调用吐司方法
        List<Destination> toasts = destinationService.queryToastsById(strategyCatalog.getDestId());
        if(toasts !=null && toasts.size()>0){
            //获取集合中第一个元素，即为国家
            Destination destination = toasts.get(0);
            if("中国".equals(destination.getName())){
                strategy.setIsabroad(Strategy.ABROAD_YES);
            }else {
                strategy.setIsabroad(Strategy.ABROAD_NO);
            }
        }
        if(StringUtils.hasLength(strategy.getId())){
            Strategy strategy1 = this.get(strategy.getId());
            strategy.setCreateTime(strategy1.getCreateTime());
            strategy.setViewnum(strategy1.getViewnum());
            strategy.setReplynum(strategy1.getFavornum());
            strategy.setSharenum(strategy1.getSharenum());
            strategy.setThumbsupnum(strategy1.getThumbsupnum());
            this.update(strategy);
         }else {
             strategy.setCreateTime(new Date());
             this.save(strategy);
         }
    }

    @Override
    public void changeState(int state, String id) {
        //部分数据更新
        Query query = new Query();
        //查询条件
        query.addCriteria(Criteria.where("_id").is(id));
        //设置更新的字段
        Update update = new Update();
        update.set("state",state);
        mongoTemplate.updateMulti(query,update,Strategy.class);
    }

    @Override
    public List<Strategy> findByCatalogId(String id) {
        return  strategyRepository.findByCatalogId(id);
    }

    @Override
    public List<Strategy> findByDestId(String id) {

        return  strategyRepository.findByDestId(id);

    }

    @Override
    public List<Strategy> viewnumTop3logs(String id) {
        //展示点击量前三的攻略
        //查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("destId").is(id));
        //分页
        Pageable pageable = PageRequest.of(0,3,Sort.Direction.DESC,"viewnum");
          query.with(pageable);
        return mongoTemplate.find(query,Strategy.class);
    }

    @Override
    public Page<Strategy> queryByTheme(StrategyQuery qo) {
        //查询对象
        Query query = new Query();
        if(StringUtils.hasLength(qo.getThemeId())){
        query.addCriteria(Criteria.where("themeId").is(qo.getThemeId()));
        }

        if(StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }

        Long totalCount = mongoTemplate.count(query, Strategy.class);
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(pageable);
        List<Strategy> strategies = mongoTemplate.find(query, Strategy.class);
        return new PageImpl(strategies,pageable,totalCount);
    }

    @Override
    public void updateStrategyVo(StrategyStatisVO vo) {
        //使用部分更新操作
        Query query = new Query();
        //指定需要id
        query.addCriteria(Criteria.where("_id").is(vo.getStrategyId()));
        Update update = new Update();
        update.set("replynum",vo.getReplynum());
        update.set("favornum",vo.getFavornum());
        update.set("thumbsupnum",vo.getThumbsupnum());
        update.set("viewnum",vo.getViewnum());
        update.set("sharenum",vo.getSharenum());
        mongoTemplate.updateMulti(query,update,Strategy.class);
    }

    @Override
    public List<Strategy> queryByDestName(String DestName) {

        return strategyRepository.findByDestName(DestName);
    }


}
